package com.book.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.springframework.stereotype.Component;

/**
 * 加密解密类
 * 
 */

@Component
public class FileEncryptGenService {

	private static final int STREAM_BUFFER_SIZE = 1024;

	/**
	 * 对文件进行加密
	 * 
	 * @param String
	 *            oldFile 原始要加密的文件
	 * @param String
	 *            newFile 加密后的文件
	 * @return
	 */
	public void encryptFile(String oldFile, String newFile) throws Exception {
		FileInputStream in = new FileInputStream(oldFile);
		File file = new File(newFile);
		if (!file.exists())
			file.createNewFile();
		FileOutputStream out = new FileOutputStream(file);
		change(in, out);
		in.close();
		out.close();
	}

	/**
	 * 对文件进行解密
	 * 
	 * @param String
	 *            oldFile 原始要解密的文件
	 * @param String
	 *            newFile 解密后的文件
	 * @return
	 */
	public void decryptFile(String oldFile, String newFile) throws Exception {
		FileInputStream in = new FileInputStream(oldFile);
		File file = new File(newFile);
		if (!file.exists())
			file.createNewFile();
		FileOutputStream out = new FileOutputStream(file);
		change(in, out);
		in.close();
		out.close();
	}

	public static void change(InputStream in, OutputStream out) throws IOException {
		byte buffer[] = new byte[STREAM_BUFFER_SIZE];
		int size;
		while ((size = in.read(buffer)) != -1) {
			for (int i = 0; i < size; i++) {
				buffer[i] = (byte) ~buffer[i];
			}
			out.write(buffer, 0, size);
		}
	}

}
